<?php
/**
 * This page is using for single page url or csv file url extraction.
 *
 * LICENSE:
 *
 * @copyright 2010 Association Management Center
 * @author    Rakesh Verma (rakesh.verma@dotsquares.com)
 * @version   2.0
 * @link
 * @since     File available since import script creation
 * @package   Joomla Article
 */

require_once 'init.php';
$msg           = $_REQUEST[msg];
$obj_page      = new pages();
$page_id       = $_REQUEST[page_id];
// pulling the page task
$task          = $_REQUEST['task'];


//admin secure login
$obj           = new ws_secure_user();
$obj->load($usr_id);
if (!$usr_id){
	$obj->usr_active = 1;
}

$savearr           = array('js','flash','document');

 if($_REQUEST[is_import_css]==1 ) {
    array_push($savearr,'css');
    } //if import script require to grab css from source URL.

 if($_REQUEST[is_import_images]==1 ) {
    array_push($savearr,'image');
  } //if import script require to grab image from source URL.



  switch ($task) {

    case 'save': //saving a submitted registration form form
	$obj_page->load_from_request();

	if($_REQUEST[is_delete_modules]==1 ) {
        $obj_page->deleteModule();
    } //if import script require to delete existing site modules.
	$url    =   $_REQUEST['page_url1'];
	//$errors = $obj_page->validate_url($url);

	$errors =  array();

	if (count($errors) != 0){ // if there are errors then redisplay the form with the errors
		//  $title = $lang['Reg_title'];
		include ABSTRACT_PRIVATE_HEADER;

		// assigning variables to the template and displaying
		$page_data     = array(	'url'          => $_REQUEST['page_url1'],
                        		'page'         => $obj_page->values,
                        		'errors'       => $errors,
                        		'cancel_link'  => $_SERVER['PHP_SELF'],
                        		"templatelist" => template::get_template_list());
		include 'templates/tpl_extract_single_url.php';
		include ABSTRACT_PRIVATE_FOOTER;

	} else {    // if there are no errors then register the member and log them in

		$existing_url  = trim($_REQUEST['page_url1']);
		extract(parse_url($existing_url));
		$domain         = $scheme .'://'. $host;
		if($_REQUEST[submit] == 'Submit'){
		$_SESSION[baseLinks] =         array( total	    =>	array(),
          							          visited   =>	array(),
          							          remaining =>  array());
		}

    $obj_page->crawl_page($existing_url,$domain);
    $cntr = 0;

		if(is_array($_SESSION[baseLinks][remaining]))
		{
			while( count($_SESSION[baseLinks][remaining]) > 0 )
			{
			  $cntr++;
			  // fetch remaining | put in visited | grab its internal URL's
			  $url = array_shift($_SESSION[baseLinks][remaining]);
			  if($cntr == 2){
			    // place this URL back in remaining list because we are resubmitting form
			    array_unshift($_SESSION[baseLinks][remaining],$url);

			    echo '<form name="frm" action="extract_complete.php?task=save" method="POST">.';
			    echo '<input type="hidden" name="template_id" value="'.$_REQUEST[template_id].'">';
			    echo '<input type="hidden" name="is_import_css" value="'.$_REQUEST[is_import_css].'">';
			    echo '<input type="hidden" name="is_html_title" value="'.$_REQUEST[is_html_title].'">';
			    echo '<input type="hidden" name="is_import_images" value="'.$_REQUEST[is_import_images].'">';
			    echo '<input type="hidden" name="is_delete_modules" value="'.$_REQUEST[is_delete_modules].'">';
			    echo '<input type="hidden" name="page_url1" value="'.$url.'">';
			    echo '<input type="hidden" name="total_extracted" value="'.($_REQUEST[total_extracted] + $cntr -1).'">';
			    echo '<input type="hidden" name="page_is_relative" value="'.$_REQUEST[page_is_relative].'">';
			    echo '</form>';
			    echo '<script>document.frm.submit();</script>';
			    exit;
			  }

			  array_push($_SESSION[baseLinks][visited],$url);
			  $obj_page->crawl_page($url,$domain);

				if($url!=''){
                 if($obj_page->checkDuplicateUrl($url)) {
                      $fcontent[]        = "URL: ";
                      $fcontent[]        = $url;
                      $fcontent[]        = " This URL is already exist.";
                      $fcontent[]        = date("m-d-Y H:i:s");

                    $file_handle   = fopen(APP_BASE_PATH."ws_joomla_import/log.csv",'a');
		            fputcsv($file_handle,$fcontent );
                    fclose($file_handle);
                 }
                 else
                 {
				  ?>
            <script>
              parent.document.getElementById('resultdiv').innerHTML = 'Currently Executing : <font color=red><b><?=$url?></b></font><br>Total Extracted:<font color=green><b><? echo ($_REQUEST[total_extracted] + $cntr);?></b></font>';
            </script>
          <?php
    			$obj_pagesave = new pages();

					$data         = $obj_pagesave->curl_data ($url);
					$data         = $obj_pagesave->filter_data($data);

					extract(parse_url($url));
					$surl         = $scheme .'://'. $host;

					//$surl               = $domain.'/';
					$origurl            =  $url;

  				//$savearr            = array('js','flash','image','css');


					//global $jsarray, $flasharray, $imagearray, $cssarray, $documentarray;

					foreach($savearr as $savecontent)
					{

					  ini_set('max_execution_time',0);
					  $obj_pagesave->grab_html_content($savecontent,$data,$surl,$origurl);
					}

					if($_REQUEST['page_is_relative']==1)
					{
					    //$data =    str_replace($surl."/","",$data);
						$data   =    $obj_pagesave->absolute_to_relative($host,$data);

					}
					$template_id  = $_REQUEST['template_id'];
					$flag         = template::get_template($template_id);
					$startflag    = trim($flag[template_start_flag]);
					$endflag      = trim($flag[template_end_flag]);
					$header       = $obj_pagesave->ExtractString($data, '',$startflag);
					$body         = $obj_pagesave->ExtractString($data, $startflag,$endflag);
					$footer       = $obj_pagesave->ExtractString($data, $endflag, '');

					$obj_pagesave->values['page_url']               = $url;
					$obj_pagesave->values['page_header']            = $header;
					$obj_pagesave->values['page_body']              = $body;
					$obj_pagesave->values['page_footer']            = $footer;
					$obj_pagesave->values['page_old_html']          = $data;
					$obj_pagesave->values['page_add_date']          = time();
					$obj_pagesave->values['page_last_modified']     = time();
					$obj_pagesave->values['page_status']            = 1;
					$obj_pagesave->values['template_id']            = $_REQUEST['template_id'];
					$obj_pagesave->values['page_is_relative']       = $_REQUEST['page_is_relative'];
            		$obj_pagesave->save();

					$pagearr      = explode("/",$url);
				  //  print_r($pagearr);
				  $pagename     = explode(".",$pagearr[count($pagearr)-1]);

       		$obj_article  = new article();
       		//template insertion in body
          //  $body1        = $startflag.$body.$endflag;
            $home         = 0;
            if(strcasecmp($url,$existing_url)){
                $home         = 1;
            }
           $istitle = 0;
           if($_REQUEST['is_html_title'] ==1)
             {
               $istitle =1;
             }

          $obj_article->add_article($url,$body,$header,$footer,$home,$data,$istitle);
               } //end of if duplicate url
				} // if url is not blank
			} // end while
		}

//		$msg = "Page(s) imported successfully";
//		header("Location: index.php?msg=".$msg);
//		exit();


// write xml file for image documentjs etc
/* foreach($savearr as $savecontent)
					{

		     $obj_pagesave->write_xml($savecontent,array_unique($_SESSION[$savecontent."array"]));
					}

$filename      = APP_TEMPLATE_UPLOAD_PATH.'templateDetails.xml';
$file_handle   = fopen($filename,'r');
$content       = fread($file_handle,filesize($filename));
$content       = str_replace('</install>','',$content);
fclose($file_handle);

$file_handle   = fopen($filename,'w');
$content       .='</install>';
fwrite($file_handle,$content);
fclose($file_handle);
*/
//// end of write xml file for image document js etc
?>
<script>
  parent.document.location.href='index.php?msg=Page(s) imported successfully';
</script>
<?php
	}
	break;

default:
	break;
}
?>